<!-- 发票统计页面 -->
<template>
  <div class="invoice-statistics-container">
    <div class="page-header">
      <h2>发票统计</h2>
      <div class="header-actions">
        <el-date-picker
            v-model="trendYear"
            :clearable="false"
            format="YYYY"
            placeholder="选择年份"
            type="year"
            value-format="YYYY"
            @change="handleYearChange"
        />
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 加载指示器 -->
    <div v-if="loading" class="loading-container">
      <el-icon :size="32" class="loading-icon">
        <Loading/>
      </el-icon>
      <p>加载统计数据中...</p>
    </div>

    <!-- 统计卡片区域 -->
    <el-row v-loading="loading" :gutter="20" class="stat-cards">
      <el-col :md="6" :sm="12" :xs="24">
        <statistics-card
            :chart-data="getMonthlyCountsData()"
            :comparison="calculateGrowthRate(overallStats.currentMonthCount, overallStats.lastMonthCount)"
            :value="overallStats.totalCount || 0"
            chart-color="#409EFF"
            chartType="line"
            comparisonLabel="与上月相比"
            icon="Ticket"
            subtitle="单位: 张"
            title="发票总数"
        />
      </el-col>
      <el-col :md="6" :sm="12" :xs="24">
        <statistics-card
            :chart-data="getMonthlyAmountsData()"
            :comparison="calculateGrowthRate(overallStats.currentMonthAmount, overallStats.lastMonthAmount)"
            :format-options="{
            style: 'decimal',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
          }"
            :value="overallStats.totalAmount || 0"
            chart-color="#67C23A"
            chartType="line"
            comparisonLabel="与上月相比"
            icon="Money"
            prefix="¥"
            subtitle="不含税"
            title="总金额"
        />
      </el-col>
      <el-col :md="6" :sm="12" :xs="24">
        <statistics-card
            :chart-data="getMonthlyTaxData()"
            :comparison="calculateGrowthRate(overallStats.currentMonthTax, overallStats.lastMonthTax)"
            :format-options="{
            style: 'decimal',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
          }"
            :value="overallStats.totalTax || 0"
            chart-color="#E6A23C"
            chartType="line"
            comparisonLabel="与上月相比"
            icon="Money"
            prefix="¥"
            subtitle="单位: 元"
            title="总税额"
        />
      </el-col>
      <el-col :md="6" :sm="12" :xs="24">
        <statistics-card
            :chart-data="getMonthlyTotalData()"
            :comparison="calculateGrowthRate(
            overallStats.currentMonthAmountWithTax,
            overallStats.lastMonthAmountWithTax
          )"
            :format-options="{
            style: 'decimal',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
          }"
            :value="overallStats.totalAmountWithTax || 0"
            chart-color="#F56C6C"
            chartType="line"
            comparisonLabel="与上月相比"
            icon="Money"
            prefix="¥"
            subtitle="单位: 元"
            title="价税合计"
        />
      </el-col>
    </el-row>

    <!-- 趋势图区域 -->
    <div class="chart-section">
      <el-card v-loading="loading" class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>月度发票金额趋势</span>
            <div class="chart-actions">
              <el-select v-model="trendYear" placeholder="选择年份" @change="handleYearChange">
                <el-option
                    v-for="year in yearOptions"
                    :key="year"
                    :label="year"
                    :value="year"
                />
              </el-select>
            </div>
          </div>
        </template>
        <div id="monthlyChart" ref="monthlyChart" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 类别分布区域 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :md="24" :xs="24">
        <el-card v-loading="loading" class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>发票类别分布</span>
            </div>
          </template>
          <div id="categoryChart" ref="categoryChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 供应商TOP5 -->
    <el-card v-loading="loading" class="chart-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>供应商TOP5（按金额）</span>
        </div>
      </template>
      <el-table :data="supplierTop5" stripe style="width: 100%">
        <el-table-column align="center" type="index" width="50"/>
        <el-table-column label="供应商" min-width="180" prop="supplierName"/>
        <el-table-column align="center" label="发票数量" width="120">
          <template #default="scope">
            {{ scope.row.count }}
          </template>
        </el-table-column>
        <el-table-column align="right" label="总金额" min-width="150">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="占比" width="100">
          <template #default="scope">
            {{ calculatePercentage(scope.row.totalAmount, supplierTotalAmount) }}%
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {computed, nextTick, onMounted, ref} from 'vue';
import * as echarts from 'echarts';
import {
  getMonthlyTrend,
  getOverallStatistics,
  getStatisticsByCategory,
  getStatisticsBySupplier
} from '@/api/statistics';
import StatisticsCard from '../../components/StatisticsCard.vue';

// 图表实例
let monthlyChartInstance: echarts.ECharts | null = null;
let categoryChartInstance: echarts.ECharts | null = null;

// 加载状态
const loading = ref(true);

// 整体统计数据
const overallStats = ref<any>({});

// 供应商数据
const supplierStats = ref<any>({});
const supplierTop5 = ref<any[]>([]);
const supplierTotalAmount = computed(() => {
  if (!supplierTop5.value.length) return 0;
  return supplierTop5.value.reduce((sum, item) => sum + parseFloat(item.totalAmount || 0), 0);
});

// 类别数据
const categoryStats = ref<any>({});
const categoryData = ref<any[]>([]);

// 趋势图年份
const currentYear = new Date().getFullYear();
const trendYear = ref<string>(currentYear.toString());
const yearOptions = computed(() => {
  const years = [];
  for (let i = currentYear - 5; i <= currentYear; i++) {
    years.push(i.toString());
  }
  return years;
});

// 月度趋势数据
const monthlyTrend = ref<any[]>([]);

// 格式化金额
const formatAmount = (amount: any): string => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 计算百分比
const calculatePercentage = (value: number, total: number): string => {
  if (!total) return '0.00';
  return ((value / total) * 100).toFixed(2);
};

// 计算增长率
const calculateGrowthRate = (current: any, previous: any) => {
  if (!previous || previous === 0) return 0;
  return Number(((current - previous) / previous * 100).toFixed(2));
};

// 获取月度数量数据
const getMonthlyCountsData = () => {
  if (!monthlyTrend.value || !monthlyTrend.value.length) return [0, 0, 0, 0, 0, 0];

  const result = monthlyTrend.value
      .slice(-6)
      .map(item => Number(item.count) || 0);

  return result;
};

// 获取月度金额数据
const getMonthlyAmountsData = () => {
  if (!monthlyTrend.value || !monthlyTrend.value.length) return [0, 0, 0, 0, 0, 0];

  const result = monthlyTrend.value
      .slice(-6)
      .map(item => parseFloat(item.amount || 0));

  return result;
};

// 获取月度税额数据
const getMonthlyTaxData = () => {
  if (!monthlyTrend.value || !monthlyTrend.value.length) return [0, 0, 0, 0, 0, 0];

  const result = monthlyTrend.value
      .slice(-6)
      .map(item => parseFloat(item.tax || 0));

  return result;
};

// 获取月度总额数据
const getMonthlyTotalData = () => {
  if (!monthlyTrend.value || !monthlyTrend.value.length) return [0, 0, 0, 0, 0, 0];

  const result = monthlyTrend.value
      .slice(-6)
      .map(item => parseFloat(item.amountWithTax || 0));

  return result;
};

// 初始化月度趋势图
const initMonthlyChart = () => {
  const chartDom = document.getElementById('monthlyChart');
  if (!chartDom) {
    return;
  }

  // 如果图表实例已存在，先销毁
  if (monthlyChartInstance) {
    monthlyChartInstance.dispose();
  }

  monthlyChartInstance = echarts.init(chartDom);

  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
  const amounts: number[] = new Array(12).fill(0);
  const counts: number[] = new Array(12).fill(0);

  if (monthlyTrend.value && monthlyTrend.value.length > 0) {
  } else {
  }

  // 如果有实际数据，则使用实际数据
  if (monthlyTrend.value && monthlyTrend.value.length > 0) {
    monthlyTrend.value.forEach((item: any) => {
      if (!item) {
        return;
      }

      // 提取月份索引 (1-12 转换为 0-11)
      let monthIndex = -1;
      const monthStr = String(item.month || '');

      if (monthStr.includes('-')) {
        // 处理 "2023-01" 格式
        monthIndex = parseInt(monthStr.split('-')[1]) - 1;
      } else {
        // 尝试直接解析为数字
        monthIndex = parseInt(monthStr) - 1;
      }

      if (monthIndex >= 0 && monthIndex < 12) {
        // 优先使用amount字段，其次是其他可能的字段名
        if (item.amount !== undefined) {
          amounts[monthIndex] = Number(item.amount);
        } else if (item.amountWithTax !== undefined) {
          amounts[monthIndex] = Number(item.amountWithTax);
        } else if (item.totalAmount !== undefined) {
          amounts[monthIndex] = Number(item.totalAmount);
        }

        // 使用count字段获取数量
        if (item.count !== undefined) {
          counts[monthIndex] = Number(item.count);
        }
      }
    });
  } else {
    // 如果没有数据，清空数组
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['金额', '数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months
    },
    yAxis: [
      {
        type: 'value',
        name: '金额',
        axisLabel: {
          formatter: '{value}元'
        }
      },
      {
        type: 'value',
        name: '数量',
        axisLabel: {
          formatter: '{value}张'
        }
      }
    ],
    series: [
      {
        name: '金额',
        type: 'bar',
        data: amounts
      },
      {
        name: '数量',
        type: 'line',
        yAxisIndex: 1,
        data: counts
      }
    ]
  };

  monthlyChartInstance.setOption(option);
};

// 初始化类别饼图
const initCategoryChart = () => {
  if (!categoryData.value.length) return;

  const chartDom = document.getElementById('categoryChart');
  if (!chartDom) return;

  categoryChartInstance = echarts.init(chartDom);

  const chartData = categoryData.value.map(item => ({
    name: item.category || '未分类',
    value: parseInt(item.count)
  }));

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: chartData.map(item => item.name)
    },
    series: [
      {
        name: '发票类别',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        },
        emphasis: {
          label: {
            show: true,
            fontWeight: 'bold'
          }
        },
        data: chartData
      }
    ]
  };

  categoryChartInstance.setOption(option);
};

// 初始化所有图表
const initCharts = async () => {
  await nextTick();
  initMonthlyChart();
  initCategoryChart();

  // 监听窗口变化，重绘图表
  window.addEventListener('resize', () => {
    monthlyChartInstance?.resize();
    categoryChartInstance?.resize();
  });
};

// 获取整体统计数据
const fetchOverallStatistics = async () => {
  try {
    const res = await getOverallStatistics();
    if (res.code === 200 && res.data) {
      overallStats.value = res.data;
    }
  } catch (error) {
  }
};

// 获取类别统计数据
const fetchCategoryStatistics = async () => {
  try {
    const res = await getStatisticsByCategory();
    if (res.code === 200 && res.data) {
      categoryStats.value = res.data;
      categoryData.value = res.data.countByCategory || [];
    }
  } catch (error) {
  }
};

// 获取供应商统计数据
const fetchSupplierStatistics = async () => {
  try {
    const res = await getStatisticsBySupplier();
    if (res.code === 200 && res.data) {
      supplierStats.value = res.data;
      supplierTop5.value = res.data.top5ByAmount || [];
    }
  } catch (error) {
  }
};

// 获取月度趋势数据
const fetchMonthlyTrend = async () => {
  try {
    // 直接传递字符串类型的年份
    const res = await getMonthlyTrend(trendYear.value);

    if (res.code === 200) {
      // 检查不同的数据结构可能性
      if (res.data && res.data.monthlyTrend && Array.isArray(res.data.monthlyTrend)) {
        // 标准结构: { code: 200, data: { monthlyTrend: [...] } }
        monthlyTrend.value = res.data.monthlyTrend;
      } else if (res.data && Array.isArray(res.data)) {
        // 数组结构: { code: 200, data: [...] }
        monthlyTrend.value = res.data;
      } else if (res.data) {
        // 其他可能的结构
        // 尝试查找包含月度数据的字段
        const dataKeys = Object.keys(res.data);

        // 寻找看起来像列表的字段
        for (const key of dataKeys) {
          if (Array.isArray(res.data[key])) {
            if (res.data[key].length > 0 && res.data[key][0].month) {
              monthlyTrend.value = res.data[key];
              break;
            }
          }
        }

        // 如果没有找到合适的字段，记录警告
        if (!monthlyTrend.value || monthlyTrend.value.length === 0) {
          console.warn('无法从响应中提取月度趋势数据:', res.data);
          monthlyTrend.value = [];
        }
      } else {
        console.warn('无法从响应中提取月度趋势数据');
        monthlyTrend.value = [];
      }
    } else {
      console.warn('获取月度趋势数据失败:', res);
      monthlyTrend.value = [];
    }

    // 无论是否有数据都初始化图表
    initMonthlyChart();
  } catch (error) {
    console.error('获取月度趋势数据失败', error);
    monthlyTrend.value = [];
    // 即使出现错误也初始化图表，显示空图表
    initMonthlyChart();
  }
};

// 处理年份变化
const handleYearChange = () => {
  refreshData();
};

// 刷新所有数据
const refreshData = async () => {
  loading.value = true;
  try {
    await Promise.all([
      fetchOverallStatistics(),
      fetchCategoryStatistics(),
      fetchSupplierStatistics(),
      fetchMonthlyTrend()
    ]);
    initCharts();
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

// 组件挂载时初始化
onMounted(() => {
  refreshData();
});
</script>

<style scoped>
.invoice-statistics-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.loading-icon {
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.stat-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart-actions {
  display: flex;
  gap: 10px;
}

#monthlyChart, #categoryChart, #statusChart {
  height: 300px;
  width: 100%;
}
</style> 